<template>
  <view class="container">
    <view class="header">
      <view class="header-title">记录列表</view>
    </view>
    
    <!-- 月经记录 -->
    <view class="section-title">月经记录</view>
    <view v-if="loading" class="loading">
      <text>加载中...</text>
    </view>
    
    <view v-else-if="periodRecords.length === 0" class="empty-records">
      <text>暂无月经记录</text>
    </view>
    
    <view v-else class="record-list">
      <uni-swipe-action>
        <uni-swipe-action-item v-for="(record, index) in periodRecords" :key="'period-'+index" 
          :right-options="swipeOptions" @click="onSwipeActionClick($event, 'period', record, index)">
          <view class="record-item">
        <view class="record-date">
          <text class="month">{{ formatDate(record.startDate, 'MM') }}月</text>
          <text class="year">{{ formatDate(record.startDate, 'YYYY') }}</text>
        </view>
        <view class="record-content">
          <view class="record-period">
            {{ formatDate(record.startDate, 'MM/DD') }} - {{ formatDate(record.endDate, 'MM/DD') }}
          </view>
          <view class="record-days">
            持续 {{ getDaysDiff(record.startDate, record.endDate) }} 天
          </view>
        </view>
        <view class="record-cycle" v-if="index < periodRecords.length - 1">
          间隔 {{ getCycleDays(record.startDate, periodRecords[index + 1].startDate) }} 天
        </view>
      </view>
        </uni-swipe-action-item>
      </uni-swipe-action>
    </view>
    
    <!-- 亲密记录 -->
    <view class="section-title intimate-section">亲密记录</view>
    <view v-if="loadingIntimate" class="loading">
      <text>加载中...</text>
    </view>
    
    <view v-else-if="intimateRecords.length === 0" class="empty-records">
      <text>暂无亲密记录</text>
    </view>
    
    <view v-else class="record-list intimate-list">
      <uni-swipe-action>
        <uni-swipe-action-item v-for="(record, index) in intimateRecords" :key="'intimate-'+index" 
          :right-options="swipeOptions" @click="onSwipeActionClick($event, 'intimate', record, index)">
          <view class="record-item intimate-item">
            <view class="record-date intimate-date">
              <text class="month">{{ formatDate(record.date, 'MM') }}月</text>
              <text class="day">{{ formatDate(record.date, 'DD') }}</text>
              <text class="year">{{ formatDate(record.date, 'YYYY') }}</text>
            </view>
            <view class="record-content">
              <view class="record-title">
                {{ formatDate(record.date, 'YYYY/MM/DD') }}
              </view>
              <view class="record-info">
                <text class="tag" :class="record.hasProtection ? 'safe-tag' : 'unsafe-tag'" @click="showProtectionModal(record, index)">
                  {{ record.hasProtection ? '有保护措施' : '无保护措施' }}
                </text>
              </view>
            </view>
            <view class="mood-level" @click="showMoodModal(record, index)">
              <text>💓 {{ record.mood || 3 }}</text>
            </view>
          </view>
        </uni-swipe-action-item>
      </uni-swipe-action>
    </view>
    
    <!-- 保护措施选择弹窗 -->
    <uni-popup ref="protectionPopup" type="dialog">
      <uni-popup-dialog
        title="更新保护措施"
        :content="'当前状态: ' + (currentRecord.hasProtection ? '有保护措施' : '无保护措施')"
        :before-close="true"
        @confirm="confirmProtection(true)"
        @close="confirmProtection(false)"
        confirmText="有保护措施"
        cancelText="无保护措施"
      ></uni-popup-dialog>
    </uni-popup>
    
    <!-- 情绪评分弹窗 -->
    <uni-popup ref="moodPopup" type="dialog">
      <view class="mood-popup-content">
        <view class="mood-popup-title">情绪评分</view>
        <view class="mood-slider">
          <view class="mood-value">{{ tempMood }}</view>
          <slider 
            :value="tempMood" 
            min="1" 
            max="5" 
            step="1" 
            show-value 
            @change="onMoodChange"
            activeColor="#FF6B6B"
          ></slider>
          <view class="mood-labels">
            <text>很糟</text>
            <text>一般</text>
            <text>很好</text>
          </view>
        </view>
        <view class="mood-btns">
          <button class="mood-btn cancel-btn" @click="closeMoodPopup">取消</button>
          <button class="mood-btn confirm-btn" @click="confirmMood">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

// 云开发相关配置
const spaceId = 'mp-f9881352-2084-4a8f-b3ef-b52bdf18452c'
const clientSecret = '7ubwCOOf8ZdSFMOUL2pd1A=='

const loading = ref(true)
const loadingIntimate = ref(true)
const periodRecords = ref([])
const intimateRecords = ref([])
const userId = ref('')

// 滑动操作按钮配置
const swipeOptions = [
  {
    text: '删除',
    style: {
      backgroundColor: '#FF5252'
    }
  }
]

// 当前操作的记录
const currentRecord = ref({})
const currentIndex = ref(-1)
const tempMood = ref(3)

// 弹窗引用
const protectionPopup = ref(null)
const moodPopup = ref(null)

onMounted(() => {
  // 检查登录状态
  checkLoginStatus()
  
  // 加载月经记录
  loadPeriodRecords()
  
  // 加载亲密记录
  loadIntimateRecords()
})

// 检查登录状态
const checkLoginStatus = () => {
  const isLogin = uni.getStorageSync('isLogin')
  if (isLogin !== 'true') {
    console.log('用户未登录，跳转到登录页')
    uni.navigateTo({
      url: '/pages/login/login'
    })
    return false
  }
  
  // 获取用户ID
  const userInfo = uni.getStorageSync('userInfo')
  if (userInfo) {
    try {
      const parsedInfo = JSON.parse(userInfo)
      userId.value = parsedInfo.userId || parsedInfo._id || ''
    } catch (e) {
      console.error('解析用户信息失败:', e)
    }
  }
  
  return true
}

// 初始化云开发
const initCloud = () => {
  return new Promise((resolve, reject) => {
    uni.showLoading({
      title: '加载中'
    })
    
    uniCloud.init({
      spaceId,
      clientSecret,
      provider: 'aliyun'
    })
    
    uni.hideLoading()
    resolve()
  })
}

// 加载月经记录
const loadPeriodRecords = async () => {
  if (!userId.value) {
    console.error('用户ID不存在，无法加载数据')
    loading.value = false
    return
  }
  
  try {
    await initCloud()
    
    // 从云函数获取经期记录
    const res = await uniCloud.callFunction({
      name: 'getPeriodRecords',
      data: {
        userId: userId.value
      }
    })
    
    if (res.result && res.result.code === 0) {
      // 处理数据，按月经周期分组
      const rawData = res.result.data
      const groupedData = groupPeriodData(rawData)
      periodRecords.value = groupedData
    } else {
      console.error('获取经期记录失败:', res)
    }
  } catch (error) {
    console.error('加载经期记录失败:', error)
    uni.showToast({
      title: '加载数据失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 加载亲密记录
const loadIntimateRecords = async () => {
  if (!userId.value) {
    console.error('用户ID不存在，无法加载数据')
    loadingIntimate.value = false
    return
  }
  
  try {
    await initCloud()
    
    // 从云函数获取亲密记录
    const res = await uniCloud.callFunction({
      name: 'getIntimateRecords',
      data: {
        userId: userId.value
      }
    })
    
    if (res.result && res.result.code === 0) {
      // 处理数据
      intimateRecords.value = res.result.data.map(item => ({
        ...item,
        date: new Date(item.date)
      }))
    } else {
      console.error('获取亲密记录失败:', res)
    }
  } catch (error) {
    console.error('加载亲密记录失败:', error)
    uni.showToast({
      title: '加载数据失败，请重试',
      icon: 'none'
    })
  } finally {
    loadingIntimate.value = false
  }
}

// 处理滑动操作点击事件
const onSwipeActionClick = async (e, type, record, index) => {
  if (e.index === 0) { // 删除按钮
    uni.showModal({
      title: '确认删除',
      content: '确定要删除这条记录吗？',
      success: async (res) => {
        if (res.confirm) {
          await deleteRecord(type, record, index)
        }
      }
    })
  }
}

// 删除记录
const deleteRecord = async (type, record, index) => {
  try {
    await initCloud()
    
    if (type === 'period') {
      // 对于月经记录，删除整个周期内的所有日期
      const deletedDates = [];
      
      // 获取周期内所有日期
      for (let d = new Date(record.startDate); d <= new Date(record.endDate); d.setDate(d.getDate() + 1)) {
        const dateString = formatDateForAPI(d);
        deletedDates.push(dateString);
        
        // 调用云函数删除每个日期的记录
        await uniCloud.callFunction({
          name: 'deletePeriodRecord',
          data: {
            userId: userId.value,
            date: dateString
          }
        });
      }
      
      // 从本地数据中删除
      periodRecords.value.splice(index, 1);
      
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      });
    } else {
      // 亲密记录只删除单天
      const dateString = formatDateForAPI(record.date);
      
      // 调用云函数删除记录
      const res = await uniCloud.callFunction({
        name: 'deleteIntimateRecord',
        data: {
          userId: userId.value,
          date: dateString
        }
      });
      
      if (res.result && res.result.code === 0) {
        // 从本地数据中删除
        intimateRecords.value.splice(index, 1);
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        });
      } else {
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        });
      }
    }
  } catch (error) {
    console.error('删除记录失败:', error);
    uni.showToast({
      title: '删除失败，请重试',
      icon: 'none'
    });
  }
}

// 格式化日期为API需要的格式
const formatDateForAPI = (date) => {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 显示保护措施选择弹窗
const showProtectionModal = (record, index) => {
  currentRecord.value = record
  currentIndex.value = index
  protectionPopup.value.open()
}

// 确认保护措施选择
const confirmProtection = async (hasProtection) => {
  // 如果状态没变，不做处理
  if (currentRecord.value.hasProtection === hasProtection) {
    protectionPopup.value.close()
    return
  }
  
  try {
    await initCloud()
    
    const record = currentRecord.value
    const dateString = formatDateForAPI(record.date)
    
    // 先删除原记录
    await uniCloud.callFunction({
      name: 'deleteIntimateRecord',
      data: {
        userId: userId.value,
        date: dateString
      }
    })
    
    // 添加新记录
    const res = await uniCloud.callFunction({
      name: 'addIntimateRecord',
      data: {
        userId: userId.value,
        date: dateString,
        hasProtection: hasProtection,
        mood: record.mood || 3,
        notes: record.notes || ''
      }
    })
    
    if (res.result && res.result.code === 0) {
      // 更新本地数据
      intimateRecords.value[currentIndex.value].hasProtection = hasProtection
      
      uni.showToast({
        title: '更新成功',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: '更新失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('更新保护措施失败:', error)
    uni.showToast({
      title: '更新失败，请重试',
      icon: 'none'
    })
  } finally {
    protectionPopup.value.close()
  }
}

// 显示情绪评分弹窗
const showMoodModal = (record, index) => {
  currentRecord.value = record
  currentIndex.value = index
  tempMood.value = record.mood || 3
  moodPopup.value.open()
}

// 情绪评分滑块变化
const onMoodChange = (e) => {
  tempMood.value = e.detail.value
}

// 关闭情绪评分弹窗
const closeMoodPopup = () => {
  moodPopup.value.close()
}

// 确认情绪评分
const confirmMood = async () => {
  // 如果评分没变，不做处理
  if (currentRecord.value.mood === tempMood.value) {
    moodPopup.value.close()
    return
  }
  
  try {
    await initCloud()
    
    const record = currentRecord.value
    const dateString = formatDateForAPI(record.date)
    
    // 先删除原记录
    await uniCloud.callFunction({
      name: 'deleteIntimateRecord',
      data: {
        userId: userId.value,
        date: dateString
      }
    })
    
    // 添加新记录
    const res = await uniCloud.callFunction({
      name: 'addIntimateRecord',
      data: {
        userId: userId.value,
        date: dateString,
        hasProtection: record.hasProtection || false,
        mood: tempMood.value,
        notes: record.notes || ''
      }
    })
    
    if (res.result && res.result.code === 0) {
      // 更新本地数据
      intimateRecords.value[currentIndex.value].mood = tempMood.value
      
      uni.showToast({
        title: '更新成功',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: '更新失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('更新情绪评分失败:', error)
    uni.showToast({
      title: '更新失败，请重试',
      icon: 'none'
    })
  } finally {
    moodPopup.value.close()
  }
}

// 将连续的经期日按周期分组
const groupPeriodData = (rawData) => {
  if (!rawData || rawData.length === 0) return []
  
  // 按日期排序
  const sortedData = [...rawData].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
  
  // 分组为经期周期
  const periods = []
  let currentPeriod = null
  
  for (const record of sortedData) {
    const currentDate = new Date(record.date)
    
    if (!currentPeriod) {
      // 第一条记录，创建新周期
      currentPeriod = {
        startDate: currentDate,
        endDate: currentDate,
        dates: [currentDate]
      }
    } else {
      // 检查是否和当前周期连续
      const lastDate = currentPeriod.dates[currentPeriod.dates.length - 1]
      const dayDiff = Math.abs(getDaysDiff(lastDate, currentDate))
      
      if (dayDiff <= 1) {
        // 连续的经期日，添加到当前周期
        currentPeriod.dates.push(currentDate)
        
        // 更新开始和结束日期
        if (currentDate.getTime() < currentPeriod.startDate.getTime()) {
          currentPeriod.startDate = currentDate
        }
        if (currentDate.getTime() > currentPeriod.endDate.getTime()) {
          currentPeriod.endDate = currentDate
        }
      } else {
        // 不连续，保存当前周期并创建新周期
        periods.push(currentPeriod)
        currentPeriod = {
          startDate: currentDate,
          endDate: currentDate,
          dates: [currentDate]
        }
      }
    }
  }
  
  // 添加最后一个周期
  if (currentPeriod) {
    periods.push(currentPeriod)
  }
  
  // 按开始日期降序排序
  return periods.sort((a, b) => b.startDate.getTime() - a.startDate.getTime())
}

function formatDate(date, format) {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  
  if (format === 'YYYY/MM/DD') return `${year}/${month}/${day}`
  if (format === 'MM/DD') return `${month}/${day}`
  if (format === 'MM') return month
  if (format === 'DD') return day
  if (format === 'YYYY') return year
  return `${year}/${month}/${day}`
}

function getDaysDiff(startDate, endDate) {
  const start = new Date(startDate)
  const end = new Date(endDate)
  const diffTime = Math.abs(end - start)
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + (end > start ? 1 : 0)
}

function getCycleDays(currentStart, nextStart) {
  const start = new Date(currentStart)
  const next = new Date(nextStart)
  const diffTime = Math.abs(next - start)
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20px 16px;
  max-width: 375px;
  margin: 0 auto;
  background-color: $background-color;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.header-title {
  font-size: 24px;
  font-weight: bold;
  color: $brand-theme-color;
  margin-left: 12px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: $brand-theme-color;
  margin: 16px 0 12px 12px;
}

.intimate-section {
  margin-top: 8px;
}

.loading, .empty-records {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  background-color: $white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  color: #666;
  font-size: 16px;
}

.record-list {
  background-color: $white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.intimate-list {
  margin-bottom: 12px;
}

.record-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
  }
}

.intimate-item {
  background-color: #fff9f9;
}

.record-date {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 60px;
  margin-right: 16px;
  
  .month {
    font-size: 16px;
    font-weight: bold;
    color: $brand-theme-color;
  }
  
  .day {
    font-size: 14px;
    font-weight: bold;
    color: $brand-theme-color;
  }
  
  .year {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
  }
}

.intimate-date {
  .month {
    color: #FF6B6B;
  }
  .day {
    color: #FF6B6B;
  }
}

.record-content {
  flex: 1;
}

.record-period {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.record-title {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.record-info {
  font-size: 14px;
  color: #666;
}

.tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: white;
}

.safe-tag {
  background-color: #4CAF50;
}

.unsafe-tag {
  background-color: #FF5252;
}

.record-days {
  font-size: 14px;
  color: #666;
}

.record-cycle {
  font-size: 14px;
  color: $brand-theme-color;
  padding: 4px 8px;
  background-color: $brand-theme-color-light;
  border-radius: 12px;
}

.mood-level {
  font-size: 16px;
  padding: 4px 8px;
  background-color: #FFE4E9;
  border-radius: 12px;
}

/* 情绪评分弹窗样式 */
.mood-popup-content {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  width: 280px;
}

.mood-popup-title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  color: $brand-theme-color;
  margin-bottom: 16px;
}

.mood-slider {
  margin: 20px 0;
}

.mood-value {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: #FF6B6B;
  margin-bottom: 8px;
}

.mood-labels {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.mood-btns {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.mood-btn {
  flex: 1;
  margin: 0 8px;
  padding: 10px 0;
  border-radius: 20px;
  font-size: 16px;
  border: none;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
}

.confirm-btn {
  background-color: $brand-theme-color;
  color: #fff;
}
</style>
